package org.ix.gateway.schedule;

import org.ix.common.utils.JsonUtils;
import org.ix.gateway.client.RoutesClient;
import org.ix.gateway.client.model.GatewayRouteResponse;
import org.ix.gateway.model.GatewayRouteDefinition;
import org.ix.gateway.service.impl.DynamicRouteServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.List;

@Component
public class DynamicRouteScheduling {

    private final Logger logger = LoggerFactory.getLogger(DynamicRouteScheduling.class);

    private final RoutesClient routesClient;
    private final DynamicRouteServiceImpl dynamicRouteService;

    /**
     * 发布路由信息的版本号
     */
    private static Long versionId = 0L;

    public DynamicRouteScheduling(RoutesClient routesClient, DynamicRouteServiceImpl dynamicRouteService) {
        this.routesClient = routesClient;
        this.dynamicRouteService = dynamicRouteService;
    }

    // 每60秒中执行一次
    @Scheduled(cron = "*/10 * * * * ?")
    public void updateRoutes() {
        try {
            Long resultVersionId = routesClient.getRoutesVersion();
            logger.info("路由版本信息：本地版本号：" + versionId + "，远程版本号：" + resultVersionId);
            if (versionId.equals(resultVersionId)) return;

            logger.info("开始拉取路由信息......");
            List<GatewayRouteResponse> routes = routesClient.getRoutes();
            logger.info("路由信息为：" + routes);
            if (routes.isEmpty()) return;
            for (GatewayRouteResponse route : routes) {
                GatewayRouteDefinition definition = new GatewayRouteDefinition();
                definition.setId(route.getId());
                URI uri = route.getUri().startsWith("http") ? UriComponentsBuilder.fromHttpUrl(route.getUri()).build().toUri() : URI.create(route.getUri());
                definition.setUri(uri);
                definition.setFilters(JsonUtils.parseList(route.getFilters(), FilterDefinition.class));
                definition.setPredicates(JsonUtils.parseList(route.getPredicates(), PredicateDefinition.class));
                definition.setMetadata(JsonUtils.parseMap(route.getMetadata(), String.class, Object.class));
                definition.setOrder(route.getRouteOrder());
                dynamicRouteService.update(definition);
            }
            versionId = resultVersionId;
        } catch (Exception e) {
            logger.error("更新路由信息失败：", e);
        }
    }
}
